
const router = require('koa-router')();
const util = require("../common/utils")
const { sequelize } = require('../common/dbs')
// typeinfo
const typeModel = require("../models/ctype")
const typeinfo = typeModel(sequelize);

const cardModel = require("../models/card")
const cardinfo = cardModel(sequelize);

// 分页查询文章
router.get('/list', async (ctx) => {
    try {

        let reqQuery = ctx.request.query;
        cardinfo.belongsTo(typeinfo, { foreignKey: 'typeid' });
        // , targetKey: 'typeid' 
        let beginTime = new Date();
        let cardData = await cardinfo.findAndCountAll(
            {
                attributes: {   // exclude排除
                    exclude: ['deletedAt', 'cHtmlContent', 'cMdContent', 'id'],
                },
                order: [  //排序 DESC ASC
                    ['createdAt', 'DESC']
                ],
                include: [
                    {
                        attributes: ['typename'],
                        model: typeinfo,
                    }
                ],
                limit: reqQuery.pageSize ? parseInt(reqQuery.pageSize) : 10,
                offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0
            }
        );
        // let endTime = new Date();
        // cardData['m'] = endTime.getTime() -  beginTime.getTime();
        // console.log();
        ctx.body = util.resultSuccess({ data: cardData });
    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ data: null });
    }
})
// 查询热门
router.get('/hot', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        cardinfo.belongsTo(typeinfo, { foreignKey: 'typeid' });
        let cardData = await cardinfo.findAll(
            {
                order: [  //排序 DESC ASC
                    ['cshow', 'DESC']
                ],
                attributes: {   // exclude排除
                    exclude: ['typeid', 'id', 'deletedAt', 'cHtmlContent', 'cMdContent'],
                },
                include: [
                    {
                        attributes: ['typename'],
                        model: typeinfo,
                    }
                ],
                limit: reqQuery.pageSize ? parseInt(reqQuery.pageSize) : 6,
                offset: reqQuery.page ? parseInt(reqQuery.page) : 0
            }
        );
        ctx.body = util.resultSuccess({ data: cardData });
    } catch (err) {
        ctx.body = util.resultError({ data: null });
    }
})
// 根据类型查询 同类型文章
router.get('/tlist', async (ctx) => {
    try {
        ctx
            .validateQuery("typeid")
            .required("必须传typeid")
            .isString()
            .trim()
        let reqQuery = ctx.request.query;
        let cardData = await cardinfo.findAll(
            {
                where: {
                    typeid: reqQuery.typeid
                },
                order: [  //排序 DESC ASC
                    ['cshow', 'DESC']
                ],
                attributes: {   // exclude排除
                    exclude: ['id', 'deletedAt', 'cHtmlContent', 'cMdContent'],
                },
                limit: reqQuery.pageSize ? parseInt(reqQuery.pageSize) : 9,
                offset: reqQuery.page ? parseInt(reqQuery.page) : 0
            }
        );
        ctx.body = util.resultSuccess({ data: cardData });
    } catch (err) {
        ctx.body = util.resultError({ data: err.message });
    }
})

// 查询详情
router.post('/detail', async (ctx) => {
    try {
        ctx
            .validateBody("cid")
            .required("必须填写cid")
            .isString()
            .trim()

        cardinfo.belongsTo(typeinfo, { foreignKey: 'typeid' });
        let reqBody = ctx.request.body;
        let cardData = await cardinfo.findOne(
            {
                attributes: {   // exclude排除
                    exclude: ['id', 'deletedAt'],
                },
                where: {
                    cid: reqBody.cid
                },
                include: [
                    {
                        attributes: ['typename'],
                        model: typeinfo,
                    }
                ],
            }
        );

        // 查询详情的时候浏览量+1
        let newShow = cardData.cshow + 1;
        let requestData = await cardinfo.update({
            cshow: newShow,
        }, {
            where: {
                cid: reqBody.cid
            }
        })

        ctx.body = util.resultSuccess({ data: cardData });
    } catch (err) {
        // console.log(err);
        ctx.body = util.resultError({ data: err.message });
    }
})


/**
 * 修改
 * */
router.post('/editById', async (ctx) => {
    try {
        ctx
            .validateBody("cid")
            .required("必须填写id")
            .isString()
            .trim()
        ctx
            .validateBody("cTitle")
            .required("标题不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("cMdContent")
            .required("内容不能为空")
            .isString()
            .trim()
        let reqBody = ctx.request.body;
        let b = {
            cimg: reqBody.cImgUrl ? reqBody.cImgUrl : '',
            ctitle: reqBody.cTitle ? reqBody.cTitle : '',
            cMdContent: reqBody.cMdContent ? reqBody.cMdContent : '',
            cHtmlContent: reqBody.cHtmlContent ? reqBody.cHtmlContent : '',
            typeid: reqBody.typeid ? reqBody.typeid : '',
            cPreface: reqBody.cPreface ? reqBody.cPreface : '',
            updatedAt: new Date()
        }
        let requestData = await cardinfo.update(b, {
            where: {
                cid: reqBody.cid
            }
        })
        if (requestData[0] > 0) {
            ctx.body = util.resultSuccess({ message: '修改成功', data: null });
        } else {
            ctx.body = util.resultError({ code: 0, message: '修改失败,id错误', data: null });
        }

    } catch (err) {
        console.log(err);
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})

/**
 * 新增
 * */
router.post('/add', async (ctx) => {
    try {
        ctx
            .validateBody("cTitle")
            .required("标题不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("cMdContent")
            .required("内容不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body;
        let requestData = await cardinfo.create({
            cimg: reqBody.cImgUrl ? reqBody.cImgUrl : '',
            ctitle: reqBody.cTitle ? reqBody.cTitle : '',
            cMdContent: reqBody.cMdContent ? reqBody.cMdContent : '',
            cHtmlContent: reqBody.cHtmlContent ? reqBody.cHtmlContent : '',
            typeid: reqBody.typeid ? reqBody.typeid : '',
            cPreface: reqBody.cPreface ? reqBody.cPreface : '',
            cid: getuuid(),
            createdAt: new Date()
        })
        if (requestData.dataValues) {
            ctx.body = util.resultSuccess({ message: '添加成功', data: requestData.dataValues });
        } else {
            ctx.body = util.resultSuccess({ code: 0, message: '添加失败', data: null });
        }
    } catch (err) {
        
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})
function getuuid() {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    // s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid;
}
/**
 * 删除
 * */
router.post('/delById', async (ctx) => {
    try {
        ctx
            .validateBody("cid")
            .required("id不能为空")
            .isString()
            .trim()

        let requestData = await cardinfo.destroy({
            where: {
                cid: ctx.vals.cid
            }
        })
        if (requestData > 0) {
            ctx.body = util.resultSuccess({ message: '删除成功' });
        } else {
            ctx.body = util.resultSuccess({ code: 0, message: '删除失败,该类型不存在', data: null });
        }
    } catch (err) {
        ctx.body = util.resultError({ code: 0, message: err.message, data: null });
    }
})

module.exports = router.routes();






